package com.cortex.papaya.search;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.util.Log;

import com.cortex.papaya.utilities.MyLog;

/**
 * @author Gal lavie
 * this class make icons search of webs in google 
 * this class get papayaCategoty and open new thread for each PapayaDocument found in PapayaCategory
 * when class finish search the class send message on finish to PapayaApplication
 * 
 *
 */

public class FetchIcons {
	private OnStateIconsChanged Statechanged;
	private List<Link> documents;
	private StartIconThread startIconThread;


	public void setDataLoadedListener(OnStateIconsChanged Statechanged){
		this.Statechanged = Statechanged;
	}
	public interface OnStateIconsChanged{
		void timeLoadIconsStarted();
		void timeLoadIconsFinished(List<Link> documents);
		void timeLoadIconsCanceled();
	}
	public void startFetching(List<Link> documents){
		cancelFetching();
		if(Statechanged != null){
			Statechanged.timeLoadIconsStarted();
		}
		this.documents = documents;
		startIconThread = new StartIconThread();
		startIconThread.execute(documents.toArray(new Link[documents.size()]));
	}
	public boolean isFetchRunning(){
		if(startIconThread.getStatus() == Status.RUNNING){
			return true;
		}
		return false;
	}
	public void cancelFetching(){
		if(startIconThread != null){
			startIconThread.cancel(true);
		}
		if(Statechanged != null){
			Statechanged.timeLoadIconsCanceled();
		}
	}
	private class StartIconThread extends AsyncTask<Link, IconDocument, Void>{

		@Override
		protected Void doInBackground(Link... params) {
			try {
				for (int i = 0; i < params.length; i++) {
					Link document = params[i];
					String iconUrl = "http://www.google.com/s2/favicons?domain=" + 
							document.getSummaryUrl();
					publishProgress(new IconDocument(document, DownloadImage(iconUrl)));
				}

			} catch (Exception e) {
				
			}
			return null;
		}
		@Override
		protected void onProgressUpdate(IconDocument... values) {
			Link document = values[0].getDocument();
			document.setImage(values[0].getIcon());
		}
		@Override
		protected void onPostExecute(Void result) {
			if(Statechanged != null){
				Statechanged.timeLoadIconsFinished(documents);
			}
		}

	}
	private InputStream OpenHttpConnection(String urlString) throws IOException {
		InputStream in = null;
		int response = -1;

		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();

		if (!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");

		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if (response == HttpURLConnection.HTTP_OK) {
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			throw new IOException("Error connecting");
		}
		return in;
	}
	private Bitmap DownloadImage(String URL) {
		Bitmap bitmap = null;
		InputStream in = null;
		try {
			in = OpenHttpConnection(URL);
			bitmap = BitmapFactory.decodeStream(in);
			in.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return bitmap;
	}
	private class IconDocument{
		private Link document;
		public Link getDocument() {
			return document;
		}
		public void setDocument(Link document) {
			this.document = document;
		}
		public Bitmap getIcon() {
			return icon;
		}
		public void setIcon(Bitmap icon) {
			this.icon = icon;
		}
		public IconDocument(Link document, Bitmap icon) {
			super();
			this.document = document;
			this.icon = icon;
		}
		private Bitmap icon;
	}
}
